<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Callback extends CI_Controller {

    public function index()
    {
        $this->load->model('user_model', 'user');

        $code = $this->input->get('code');
        $state = $this->input->get('state');

        $_state = $this->session->userdata('state');
        if (empty($code) || empty($_state) || $_state !== $state) {
            show_error('错误', $status_code=403, $heading='拒绝访问');
        }
        $this->weixin->set_code($code);
        $token = $this->weixin->get_token();

        $this->weixin->set_token($token);

        // $user_info = $this->weixin->get_user_info($token['openid']);
        $user_info = array('openid'=>$token['openid']);
        // var_dump($user_info);
        $_user = $this->user->get_user_by_openid($token['openid']);
        if (empty($_user)) {
            $this->user->insert($user_info);
        }
        $this->session->set_userdata('user', $token['openid']);
        // echo 'test';
        redirect(site_url(), 301);

    }

    public function clear()
    {
        $this->session->sess_destroy();
        echo 'done';
    }

    public function authorize()
    {
        $openid = $this->session->userdata('user');
        if ($openid) {
            // echo 'test' . $openid .'test';
            // exit;
            redirect(site_url(), 301);
        }

        // $this->load->model('user_model', 'user');
        // $user_info = $this->user->get_user_by_openid($openid);
        // echo 'ttt' . $openid . 'tttttttttttt';
        // var_dump($user_info);
        // exit;
        // if ($user_info) {
        //     redirect(site_url(), 301);
        // }


        // $config = array('app_id' => 'wx186958a84617e867',
        //              'app_sercret' => '12e75aabd90ab2e034941f61f0c8d0aa',
        //              'redirect_uri' => site_url('callback'));
        // $state = random_string('sha1');
        // $this->session->set_userdata('state', $state);
        $url = $this->weixin->get_authorize_url($scope = 'snsapi_base');
        // echo $url;
        // exit;
        redirect($url);
    }

    public function refresh_token()
    {
        $token = $this->input->get('refresh_token');
        $this->weixin->set_token($token);
    }
}
